package priv.pfz.basedao.jdbctemplate.sqlprovider;

import com.google.common.collect.Lists;
import priv.pfz.basedao.Utils;
import priv.pfz.basedao.info.DaoInfo;
import priv.pfz.basedao.info.FieldInfo;
import priv.pfz.basedao.jdbctemplate.SqlResult;
import priv.pfz.basedao.sharding.ShardingInfo;
import priv.pfz.basedao.sharding.ShardingManager;
import priv.pfz.basedao.sqlbuilder.SQL;

import java.util.List;
import java.util.Map;

/**
 * SELECT a,b,c FROM table WHERE a=example.a AND b=example.b
 * @author yyjxp
 * 2024/1/28 23:55
 */
public class ListByExampleSqlProvider extends BaseSqlProvider {

    public static SqlResult provideSql(Object example, ShardingInfo shardingInfoParam, DaoInfo daoInfo) {
        Utils.checkNotNull(example, "example不能为空");
        Map<String, Object> valueMap = getValueMap(daoInfo, example);
        Utils.checkNotEmpty(valueMap, "example字段不能全部为空");
        ShardingManager shardingManager = new ShardingManager(daoInfo, shardingInfoParam);
        List<Object> argList = Lists.newArrayList();

        SQL sql = new SQL();
        sql.SELECT(daoInfo.getSelectColumns());
        for (FieldInfo fieldInfo : daoInfo.getFieldInfos()) {
            if (!valueMap.containsKey(fieldInfo.getFieldName())) {
                continue;
            }
            sql.WHERE(getFieldEquals(fieldInfo));
            Object value = valueMap.get(fieldInfo.getFieldName());
            shardingManager.addShardingInfo(fieldInfo, value);
            argList.add(value);
        }
        if (daoInfo.isEnableLogicDelete()) {
            sql.WHERE(getLogicDeleteWhere(daoInfo));
        }
        sql.FROM(shardingManager.getShardingTable());
        String sqlStr = sql.toString();
        sqlStr += shardingManager.getThirdShardingStr();

        System.out.println(sqlStr);
        System.out.println(argList);
        return new SqlResult(sqlStr, argList);
    }
}
